package cn.zorbus.laian.application.service;

import cn.zorbus.laian.domain.entity.SwitchEntity;
import cn.zorbus.laian.domain.repository.ISwitchRepository;
import cn.zorbus.laian.infrastructure.common.command.ChangeSwitchCommand;
import cn.zorbus.laian.infrastructure.config.GlobalFlag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.Collection;
import java.util.concurrent.Semaphore;

/**
 * create in 2023/12/1 19:56
 *
 * @author shishaodong
 * @version 0.0.1
 */
@Slf4j
@Service
@Validated
@RequiredArgsConstructor
public class SwitchService {

    private final ISwitchRepository repository;

    private final GlobalFlag globalFlag;


    public Collection<SwitchEntity> switchList() {
        return repository.findAll();
    }

    @Async
    public void switchMain(int id) {
        globalFlag.check(id);
        repository.switchMain(id);
    }

    @Async
    public void switchSingle(@NotNull ChangeSwitchCommand command) {
        if (0 == command.status()) {
            globalFlag.check(command.id());
        }
        repository.updateStatusById(command.id(), command.status());
    }
}
